<?php

namespace Beerus\Modules\Activity\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\model\activity\Kohler;
use Doraemon\tools\Hhzurl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class KohlerController extends Controller
{
    public const  PAGE_SIZE = 20;

    /**
     * 科勒活动页
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function kohler(Request $request, Content $content): Content
    {
        $list = Kohler::getList();
        $days = array_column($list, 'show_day');
        $days = array_unique(array_filter($days));
        sort($days);
        $dayListArr = [];
        foreach ($list as $row) {
            $dayListArr[$row['show_day']][] = $row;
        }
        $today = date('Ymd');
        if (empty($days)) {
            $days[] = $today;
        }
        $tab = new Tab();
        foreach ($days as $day) {
            $dayList = $dayListArr[$day] ?? [];
            $gridModel = new GridDataModel($dayList);
            $grid = Admin::grid($gridModel,
                function (Grid $grid) use ($gridModel, $day) {
                    $grid->tools(function ($tool) use ($day) {
                        $url = Hhzurl::getDomain() . '/activity/kele?day=' . $day;
                        $tool->append('<a class="btn btn-info" href="javascript:layer.open({
                                type: 2,
                                title: \'预览活动页\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'500px\', \'600px\'],
                                content: \'' . $url . '\'
                            });
               ">预览活动页</a>');
                        $tool->append('<a class="btn btn-info" href="' . $url . '" target="_blank">打开活动页</a>');
                    });
                    $grid->disableFilter();
                    $grid->disablePagination();
                    $grid->disableExport();
                    $grid->disableRowSelector();
                    $grid->column('id', '主键ID')->sort();
                    $grid->column('tab_img_url', 'tab图')->image();
                    $grid->column('poster_url', '视频封面图')->image();
                    $grid->column('video_play_url', '视频播放地址')->copyable()->display(function () {
                        $urlArr = parse_url($this->video_play_url);
                        $playUrl = '//' . $urlArr['host'] . $urlArr['path'];
                        $html = '<ul class="list-unstyled">';
                        $html .= '<li><a href="javascript:void(0);" class="grid-column-copyable text-muted" data-content="' . $this->video_play_url . '" title="Copied!" data-placement="bottom"><i class="fa fa-copy"></i></a>';
                        $html .= '<a href="javascript:layer.open({
                                type: 2,
                                title: \'预览视频\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'500px\', \'600px\'],
                                content: \'' . $playUrl . '\'
                            });
               ">预览视频</a></li>';
                        $html .= '</ul>';
                        return $html;
                    });
                    $grid->column('addtime', '添加时间');
                    $grid->column('edittime', '更新时间');
                    $grid->actions(function (Grid\Displayers\Actions $actions) {
                        $actions->disableDelete();
                    });
                }
            );

            $active = ($day == $today) ? true : false;
            $tab->add($day ?: '无', $grid->render(), $active);
        }

        return $content->row($tab)
            ->header('科勒活动页')
            ->description(' ')
            ->breadcrumb(['text' => '科勒活动页', 'url' => url('admin/activity/kohler/2023')]);
    }

    public function kohlerDetail(Request $request, Content $content, $id = 0): Content
    {
        $info = [];
        if ($id) {
            $info = Kohler::getInfo($id);
            $info['show_day'] = date('Y-m-d', strtotime($info['show_day']));
        }
        $form = new Form($info);
        if ($info['id']) {
            $form->text('id', '配置ID')->readonly();
        }
        $form->date('show_day', '展示日期')->required()->help('展示日期必填');
        $form->imgUpload('tab_img', 'tab图片');
        $form->videoUpload('video_id', '视频')->help('请注意，视频上传成功后再保存。视频最大不能超过60M。');
        $form->imgUpload('video_cover_url', '视频封面图');
        $form->action(url('admin/activity/kohler/2023/save'));
        return $content->header('配置详情')->breadcrumb(
            ['text' => '科勒活动页', 'url' => url('admin/activity/kohler/2023')],
            ['text' => '配置详情'])
            ->row($form->render());
    }

    public function kohlerSave(Request $request)
    {
        try {
            $params = $request->all();
            $id = isset($params['id']) ? $params['id'] : 0;
            $videoId = $params['video_id'] ?? '';
            $tabImg = $params['tab_img'] ?? '';
            $data = [
                'tab_img' => $tabImg,
                'show_day' => date('Ymd', strtotime($params['show_day'])),
                'video_cover_url' => $params['video_cover_url']
            ];
            if ($videoId) {
                $data['video_id'] = $videoId;
            }
            if (empty($data)) {
                throw new \Exception('视频信息错误');
            }
            if ($id) {
                $data['edittime'] = date('Y-m-d H:i:s');
                $res = Kohler::update($data, ['id' => $id]);
                $result = $res->rowCount();
            } else {
                $data['addtime'] = date('Y-m-d H:i:s');
                $data['edittime'] = date('Y-m-d H:i:s');
                $res = Kohler::insert($data);
                $result = $res->rowCount();
            }
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            if ($result) {
                return redirect(url('admin/activity/kohler/2023'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function kohlerSort(Request $request)
    {
        $sortArr = $request->input('sort', '');
        if ($sortArr) {
            foreach ($sortArr as $id => $sort) {
                Kohler::update(['sort' => $sort], ['id' => $id]);
            }
        }

    }

}